package cn.edu.bit.dm.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import java.sql.PreparedStatement;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.bit.dto.WebPage;
@Component
@Scope("prototype")
public class DefaultDao implements BaseDao {

	@Autowired
	@Qualifier("url")
	private String url;
	@Autowired
	@Qualifier("user")
	private String user;
	@Autowired
	@Qualifier("password")
	private String password;
	
	
	private Connection conn;
	private ResultSet rs;
	private PreparedStatement pstmt;
	
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {			
			e.printStackTrace();
		}
	}
	
	@Override
	public ArrayList<WebPage> query(String keyword, int limit, int offset) {
		ArrayList<WebPage> result = null;		
		try {
			if(conn==null){
				conn = DriverManager.getConnection(url,user,password);
			}
			pstmt = conn.prepareStatement("SELECT url,title,content FROM HugeTable WHERE MATCH(url,title,content) AGAINST(? IN BOOLEAN MODE) LIMIT ?,?");
			pstmt.setString(1, keyword);
			pstmt.setInt(2, offset);
			pstmt.setInt(3, limit);
			rs = pstmt.executeQuery();
			result = new ArrayList<WebPage>();
			while(rs.next()){
				WebPage webPage = new WebPage();
				webPage.setURL(rs.getString("url"));
				webPage.setTitle(rs.getString("title"));
				webPage.setContent(rs.getString("content"));
				result.add(webPage);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return result;
	}

	@Override
	public int queryCount(String keyword) {
		int result = 0;
		try {
			if(conn==null){
				conn = DriverManager.getConnection(url,user,password);
			}
			pstmt = conn.prepareStatement("SELECT COUNT(*) FROM HugeTable WHERE MATCH(url,title,content) AGAINST(? IN BOOLEAN MODE)");
			pstmt.setString(1, keyword);			
			rs = pstmt.executeQuery();
			rs.next();
			result = rs.getInt(1);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return result;
	}

	public void dispose(){
		try {
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {				
			e.printStackTrace();
		}finally{
			try{
				if(pstmt!=null){
					pstmt.close();
				}
			}catch (SQLException e){
				e.printStackTrace();
			}			
		}		
	}

	
}
